package com.gjxx.common.repository;


import com.gjxx.common.utils.spring.SpringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zha on 2018/6/14.
 */
public abstract class BaseRepository {

    public abstract String getCacheName();

    private static Map<String, Map<String, Object>> cacheMap = new ConcurrentHashMap<>();

    private String getKey(String key) {
        return key;
    }

    /**
     * 获取当前缓存map
     *
     * @return
     */
    private Map<String, Object> getCacheMap() {

        if (cacheMap.containsKey(this.getCacheName())) return cacheMap.get(this.getCacheName());

        Map<String, Object> cacheItemMap = new ConcurrentHashMap<>();
        cacheMap.put(this.getCacheName(), cacheItemMap);

        return cacheItemMap;
    }

    public <T> T getService(String beanName, Class<T> clazz) {
        return SpringUtils.getBean(clazz);
    }

    public Object getService(String beanName) {
        return SpringUtils.getBean(beanName);
    }

    public void removeCachedValue(String key) {

        this.getCacheMap().remove(this.getKey(key));

    }

    @SuppressWarnings("unchecked")
    public <T> T getCacheValue(String key, Class<T> clazz) {

        Object value = this.getCacheMap().get(this.getKey(key));
        if (value != null) return (T) value;
        return null;
    }

    public Object getCacheValue(String key) {

        return this.getCacheMap().get(this.getKey(key));
    }

    public void setCacheValue(String key, Object value) {

        this.getCacheMap().put(this.getKey(key), value);
    }

}
